/**
 * Created by JLB1 on 2017/1/20.
 */
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import wx from 'wx';

import AJAX from '../../lib/ajax';
import Tools from '../../lib/tools';
import Rules from '../../lib/rules';

import { addErrorListener } from '../../lib/handleError'
import weixinShare from '../../lib/weixinShare';
const Toast = require('../MyPackage/components/Toast')

require('../../lib/rem')
require('../../styles/common.less');
require('./TopUp.less')
require('../../styles/lux.less')

const isShow = true;

class TopUp extends Component {
    constructor(props) {
        super(props);
        this.state = {
            changeItem: 'pay1',  //默认两元
            changeCount: '', //充值金额(分)
            pay_style: true,   //勾选充值方式  默认选中
            personal_balance: 0,    //账户余额
        };
        this.changePayItem = this.changePayItem.bind(this);     //选择充值金额
        this.handleInputCount = this.handleInputCount.bind(this);     //输入充值金额
        this.topay = this.topay.bind(this);
        this.wxPay = this.wxPay.bind(this);
        this.selectPayStyle = this.selectPayStyle.bind(this);   //选择支付方式
        this.getAccount = this.getAccount.bind(this);
        this.paySubmit = this.paySubmit.bind(this);
    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll();
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()

        AJAX.request('user_home', {}, (data) => {
            if (data.code === 0) {
                const dataBody = data.body || {};
                const account = dataBody.account || {};
                this.setState({
                    personal_balance: account.balance
                })
            }
        })
    }

    getAccount = () => {
        AJAX.request('user_home', {}, (data) => {
            if (data.code === 0) {
                const { account } = data.body;
                this.setState({
                    personal_balance: account.balance
                })
            }
        })
    }

    changePayItem = style => {
        this.setState({
            changeItem: style,
        })
    }

    //输入充值金额
    handleInputCount = e => {
        var { value } = e.target;

        if (Rules.payMoney(value)) {
            this.setState({
                changeCount: value
            })
        }
    }

    wxPay = (params) => {
        AJAX.request('get_signature', {
            full_url: window.location.href
        }, (data) => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
            wx.ready(() => {
                wx.chooseWXPay({
                    timestamp: params.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
                    package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: params.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: params.paySign, // 支付签名
                    success: () => {
                        // 支付成功后的回调函数
                        AJAX.request('user_home', {}, (data) => {
                            if (data.code === 0) {
                                const { account } = data.body;

                                const { order_id, cbUrl } = Tools.getParams();
                                cbUrl && location.replace(location.protocol + '//' + location.host + '/' + cbUrl + '?order_id=' + order_id);

                                this.setState({
                                    personal_balance: account.balance,
                                })
                            }
                        })
                    }
                })
            })
        })
    }

    //选择支付方式
    selectPayStyle = () => {
        this.setState({
            pay_style: !this.state.pay_style
        })
    }


    //支付按钮点击去支付
    topay = () => {
        const { pay_style, changeItem, changeCount } = this.state;

        if (!pay_style) {
            this.warn('请选择支付方式');
            return
        }
        switch (changeItem) {
            case 'pay1':
                this.paySubmit(200)
                break;
            case 'pay2':
                this.paySubmit(500)
                break;
            case 'pay3':
                this.paySubmit(1000)
                break;
            case 'pay4':
                if (!changeCount || changeCount === '0') {
                    this.warn('请选择或输入金额');
                    return
                }
                this.paySubmit(parseInt(changeCount * 100));
                break;
            default:
                this.warn('请选择或输入金额');
                break
        }
    }

    //支付提交
    paySubmit(paycount) {
        AJAX.request('recharge_submit', { total_fee: paycount }, (data) => {
            if (data.body.trade) {
                //成功，调用微信支付
                this.wxPay(data.body.trade.prepay)
            }
        })
    }


    //toast弹窗
    warn(content) {
        Toast.warn({
            content: content
        })
    }

    success() {
        Toast.success({
            content: '成功'
        })
    }

    error() {
        Toast.error({
            content: '失败'
        })
    }

    loading() {
        Toast.loading({
            content: '数据加载中'
        })
    }


    render() {
        const { personal_balance, changeItem, changeCount, pay_style } = this.state;
        return (
            <div className="main_diy">
                <div className="balanceBox">
                    <div className="balanceShow">
                        <p className="balanceTitle">
                            <i className="iconfont textBlue icon-icon"></i>
                        </p>
                        <p className="balanceNum">
                            余额 <span>{(personal_balance / 100).toFixed(2)}</span>
                        </p>
                    </div>

                    <div
                        className="Details"
                        onClick={() => window.location.href = './AccountDetail'}
                    >
                        <span className="cusp"></span>
                        <p className="DetailsTitle">明细 </p>
                    </div>
                </div>


                <p className="topUpNumTitle">
                    <span>充值金额</span>
                </p>

                <ul className="numBox">
                    <li
                        className={`numItem ${changeItem == 'pay1' ? '' + ' bg_Y' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay1')}
                    >
                        2元
                    </li>
                    <li className="gap"></li>
                    <li
                        className={`numItem ${changeItem == 'pay2' ? '' + ' bg_Y' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay2')}
                    >
                        5元
                    </li>
                </ul>

                <ul className="numBox">
                    <li
                        className={`numItem ${changeItem == 'pay3' ? '' + ' bg_Y' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay3')}
                    >
                        10元
                    </li>
                    <li className="gap"></li>
                    <li className='numItem'
                        onClick={this.changePayItem.bind(this, 'pay4')}>
                        <input
                            className={`selfNum ${changeItem == 'pay4' ? '' + ' bg_Y' : + '' + ' bg_G'}`}
                            value={changeCount}
                            placeholder="输入任意金额"
                            onChange={this.handleInputCount}
                        />
                    </li>
                </ul>

                <p className="payStyle">充值方式</p>

                <div className="payStyleList">
                    <div
                        className="payStyleList_left lux-ai-c"
                        onClick={this.selectPayStyle}
                    >
                        <i className="iconfont textGreen icon-iconfontweixin"></i>
                        <span>微信支付</span>
                    </div>
                    <i className={`payStyleList_right iconfont textYellow ${pay_style ? 'icon-duigou' : + ''}`}></i>
                </div>

                <div className="handleBtnGroup">
                    <a
                        href="javascript:;"
                        className="weui-btn yellow weui-btn_warn"
                        onClick={this.topay}
                    >
                        立即充值
                    </a>
                </div>

            </div>
        )
    }
}

ReactDOM.render(<TopUp />, document.getElementById('app'))
if (module.hot) {
    module.hot.accept();
}
